<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
        v-model="user.username"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="user.pwd"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="submit"> 登录 </van-button>
      <van-button
        @click="router.replace('/reg')"
        block
        round
        style="margin-top: 5px"
        type="warning"
        >去注册</van-button
      >
    </div>
  </van-form>
</template>

<script setup lang="ts" name="Register">
import { reactive } from "vue";
import { useRouter, useRoute } from "vue-router";
import api from "@a/index";
import { showSuccessToast, showFailToast } from "vant";
import vueCookie from "@/utils/cookie";
const router = useRouter();
const route = useRoute();
const user = reactive({
  username: "",
  pwd: "",
});
const onSubmit = () => {
  api
    .userLogin({
      ...user,
      deviceId: "ss",
      deviceName: "dede",
    })
    .then((res) => {
      if (res.data.code === 0) {
        vueCookie.setCookie("token", res.data.data.token);
        vueCookie.setCookie("uid", res.data.data.uid);
        showSuccessToast({
          message: "用户登录成功",
          duration: 2000,
          onClose: () => {
            if (route.query.redirect) {
              router.replace(route.query.redirect as string);
            } else {
              router.replace("/home");
            }
          },
        });
      } else {
        showFailToast("登录失败");
      }
    });
};
</script>

<style scoped></style>
